package com.example.service.impl;

import cn.hutool.http.HttpRequest;
import com.example.common.Result;
import com.example.service.PhoneService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class PhoneServiceImpl implements PhoneService {


    @Override
    public Object queryByPhone(String phone) throws JsonProcessingException {
        // 手机号格式的基础校验，正则表达式
        String phonePattern = "^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}$";
        if(!phone.matches(phonePattern)) {
            return Result.error("手机号格式不正确"); // 对象
        }
        // 发请求
        String url = "https://eolink.o.apispace.com/teladress/teladress";
        String token = "76ihq05r8wzqst05384mwvllxrs2y3vy";
        String json = HttpRequest.post(url)
                .header("X-APISpace-Token", token)
                .header("Content-Type",
                        "application/x-www-form-urlencoded")
                .form("mobile", phone)
                .execute().body();
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.readValue(json, Map.class);
    }
}
